package main

import (
	"net/http"
	"strconv"
	"text/template"
	"time"
)

type User struct {
	ID   int64
	Name string
	Sex  bool
	Addr string
}

func main() {
	users := []*User{
		{1, "a1", true, "xxxxxx"},
		{2, "a2", false, "yyyyyy"},
		{3, "a3", true, "zzzzzz"},
	}
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// fmt.Fprintf(w, "用户页面")
		tpl := template.Must(template.ParseFiles("./template/user.html"))
		tpl.ExecuteTemplate(w, "user.html", users)
	})

	http.HandleFunc("/create/", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			tpl := template.Must(template.ParseFiles("./template/create.html"))
			tpl.ExecuteTemplate(w, "create.html", nil)
		} else {
			// tpl := template.Must(template.ParseFiles("./template/create.html"))
			r.ParseForm()
			values := r.PostForm
			values.Get("name")
			users = append(users, &User{
				time.Now().Unix(),
				values.Get("name"),
				values.Get("sex") == "1",
				values.Get("addr"),
			})

			http.Redirect(w, r, "/", 302)
			// tpl.ExecuteTemplate(w, "create.html", users)
		}

	})

	http.HandleFunc("/delete/", func(w http.ResponseWriter, r *http.Request) {
		if id, err := strconv.ParseInt(r.FormValue("id"), 10, 64); err == nil {
			nUsers := make([]*User, 0)
			for _, user := range users {
				if user.ID == id {
					continue
				}
				nUsers = append(nUsers, user)
			}
			users = nUsers
		}
		http.Redirect(w, r, "/", 302)
	})

	http.ListenAndServe(":19999", nil)
}
